package com.taoist_awei.blog.infrastructure.repository;

import com.taoist_awei.blog.core.UserEntity;
import com.taoist_awei.blog.core.UserRepository;
import com.taoist_awei.blog.infrastructure.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
public class MyBatisUserRepository implements UserRepository {
    private final UserMapper userMapper;

    @Autowired
    public MyBatisUserRepository(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public Optional<UserEntity> findUserById(String id) {
        return Optional.ofNullable(userMapper.findUserById(id));
    }

    @Override
    public Optional<UserEntity> findUserByEmail(String email) {
        return Optional.ofNullable(userMapper.findUserByEmail(email));
    }

    @Override
    public void save(UserEntity user) {
        if (userMapper.findUserById(user.getUserId()) != null) {
            userMapper.updateUser(user);
        } else {
            userMapper.insertUser(user);
        }
    }
}
